<?php

namespace App\Admin\Controllers;

use App\Actions\Admin\ConfigAction;
use App\Models\Config;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;

class ConfigController extends AdminController
{
    protected $title = '系统配置';
    
    public function index(Content $content)
    {
        if (strtolower(request()->method()) == 'get') {
            return $content->title($this->title())->body($this->form());
        } else {
            return $this->form()->store();
        }
        
    }

    protected function form()
    {
        Admin::style(controllerFormStyle());
        return Form::make(new Config(), function (Form $form) {
            $keys = Config::query()->whereNotIn('key', ['dy_statistic'])->orderBy('position', 'asc')->pluck('title', 'key')->all();
            $values = Config::query()->pluck('value', 'key')->all();
            foreach($keys as $field => $title) {
                $value = isset($values[$field]) ? $values[$field] : null;
                if (in_array($field, ['ddb_first_end', 'ddb_second_end', 'dy_end'])) {
                    $form->datetime($field, $title)->default($value)->value($value);
                } else {
                    $form->text($field, $title)->default($value)->value($value);
                }
            }

            $form->action(admin_route('config'));
            $form->saving(function(Form $form) {
                try {
                    $inputs = request()->all();
                    ConfigAction::make()->save($inputs);
                } catch (\Throwable $th) {
                    return $form->response()->error('保存失败');
                }
                return $form->response()->success('保存成功')->refresh();
            });
        });
    }
}
